<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="工单编号" prop="workNumber">
        <el-input
          v-model="queryParams.workNumber"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="工单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择工单类型" class="width_100" @change="handleQuery">
          <el-option
            v-for="item in orderTypeList"
            :key="item.dictCode"
            :label="item.dictValue"
            :value="item.dictCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择工单状态" class="width_100" @change="handleQuery">
          <el-option
            v-for="item in orderStatusList"
            :key="item.key"
            :label="item.label"
            :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>
     <!-- <el-form-item label="计划完成时间" prop="planTime" label-width="100px">
        <el-date-picker clearable
          v-model="queryParams.planTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择计划完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理人" prop="dealPerson">
        <el-input
          v-model="queryParams.dealPerson"
          placeholder="请输入处理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单来源" prop="origin">
        <el-input
          v-model="queryParams.origin"
          placeholder="请输入工单来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
    <!--  <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workOrder:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workOrder:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workOrder:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['workOrder:order:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="workNumber" width="140"/>
<!--      <el-table-column label="项目代码" align="center" prop="projectCode" width="130"/>-->
      <el-table-column label="工单名称" align="center" prop="name" />
      <el-table-column label="工单类型" align="center" prop="type" width="230">
        <template slot-scope="scope">
          <span>{{orderTypeObject[scope.row.type]}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="工单内容" align="center" prop="contents" /> -->
      <el-table-column label="计划完成时间" align="center" prop="planTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="dealPerson" width="80">
        <template slot-scope="scope">
          <span v-if="dealPersonList.indexOf(scope['row']['dealPerson']) != '-1'">{{personObject[scope.row.dealPerson]}}</span>
          <span v-else>{{scope.row.dealPerson}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="处理记录" align="center" prop="dealLog" /> -->
      <el-table-column label="状态" align="center" prop="status" width="140">
        <template slot-scope="scope">
          <el-tag type="info"  v-if="scope.row.status == -1">创建中</el-tag>
          <el-tag v-if="scope.row.status == 0">待处理</el-tag>
          <el-tag type="info" v-else-if="scope.row.status == 1">处理中</el-tag>
          <el-tag type="success" v-else-if="scope.row.status == 2">已完成</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status == 3">已延期</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status == 4">已关闭</el-tag>
        </template>
      </el-table-column>
     <!-- <el-table-column label="工单来源" align="center" prop="origin" width="120"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['workOrder:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workOrder:order:remove']"
          >删除</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="check(scope.row.id)"
          >查看</el-button>
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="acceptCase(scope.row.workNumber)"
          >受理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">

        <el-form-item label="工单编号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工单编号" :disabled="checkDisabled"/>
        </el-form-item>
        <!--<el-form-item label="项目代码" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目代码" />
        </el-form-item>-->
        <el-form-item label="工单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入工单名称" :disabled="checkDisabled"/>
        </el-form-item>
        <el-form-item label="工单类型" prop="type">
          <!--<div v-if="typeMark != 'view'">-->
            <el-select v-model="form.type" placeholder="请选择工单类型" class="width_100" :disabled="checkDisabled">
              <el-option
                v-for="item in orderTypeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode">
              </el-option>
            </el-select>
          <!--</div>
          <div v-else>{{form.status == '0' ? '未启动' : form.status == '1' ? '执行中' : form.status == '2' ? '已完成' : '关闭'}}</div>-->
        </el-form-item>
        <el-form-item label="工单内容" prop="contents">
          <el-input v-model="form.contents" type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入内容" :disabled="checkDisabled"/>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="planTime">
          <el-date-picker clearable :disabled="checkDisabled"
            v-model="form.planTime"
            type="date"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理人" prop="dealPerson">
          <el-input v-model="form.dealPerson" placeholder="请输入处理人" :disabled="checkDisabled"/>
        </el-form-item>
        <el-form-item label="处理记录" prop="dealLog">
          <el-input v-model="form.dealLog" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" placeholder="请输入内容" :disabled="checkDisabled"/>
        </el-form-item>
        <el-form-item label="工单来源" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入工单来源" :disabled="checkDisabled"/>
        </el-form-item>
        <el-form-item label="工单附件上传">
          <div v-for="(item, index) in fileList" :key="index">
            <el-link :underline="false" >
              <span class="el-icon-document" @click="downloadFile(item.url, item.name)"> {{ item.name }} </span>
            </el-link>

          </div>
          <!--<el-upload
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            action="/upload"
            :on-success="handleSuccess"
            :show-file-list="false"
            multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>-->
        </el-form-item>
        <el-form-item label="处理过程附件上传">
          <!--<el-upload
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            action="/upload"
            :on-success="processHandleSuccess"
            :show-file-list="false"
            multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>-->
          <div v-for="(item, index) in fileProcessList" :key="index">
            <el-link :underline="false" >
              <span class="el-icon-document" @click="downloadFile(item.url, item.name)"> {{ item.name }} </span>
            </el-link>
          </div>
        </el-form-item>
        <el-form-item v-if="form.id && checkDisabled" class="table-diy" label="工单流转记录" label-position="left" label-width="100px">
          <el-table v-if="checkDisabled" :data="form.orderLogs" style="width: 100%">
            <el-table-column prop="contents" align="center" label="处理操作" />
            <el-table-column prop="createTime" align="center" label="日期" width="100"/>
            <el-table-column prop="createBy" align="center" label="操作人" width="90"/>
            <el-table-column prop="remark" align="left" label="备注" width="150" />
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--<el-button type="primary" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancel">取 消</el-button>
      </div>


    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/workOrder/order";
import { pickupPersonList,orderDetail,acceptCaseOrder } from "@/api/workOrder/myOrder";
import { getToken } from '@/utils/auth';
import { getDicts } from '@/api/system/dict/data';

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单明细表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      orderTypeList: [
      /*    {
              key: '0',
              label: '项目运维工单'
          },
          {
              key: '1',
              label: '系统工单'
          },
          {
              key: '2',
              label: '设备更换工单'
          },
          {
              key: '3',
              label: '需求工单'
          }*/
      ],
      orderTypeObject: {},
      orderStatusList: [
          {
              key: '0',
              label: '待处理'
          },
          {
              key: '1',
              label: '处理中'
          },
          {
              key: '2',
              label: '已完成'
          },
          {
              key: '3',
              label: '已延期'
          },
          {
              key: '4',
              label: '已关闭'
          }
      ],
      Authorization: 'Bearer ' + getToken(),
      checkDisabled: true,
      personObject: {},
      dealPersonList: [],
      fileProcessList: [],
      fileList: []
    };
  },
  props: ['currentProject'],
 // dicts: [this.currentProject+'_gdlx'],
  mounted() {
    this.getList();
    this.getPersonList();
    this.getOrderTypeList();
  },
  methods: {
     downloadFile(url, fileName) {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
          const downloadUrl = URL.createObjectURL(blob);

          const link = document.createElement('a');
          link.href = downloadUrl;
          link.download = fileName;
          link.click();

          URL.revokeObjectURL(downloadUrl);
        }
      };

      xhr.send();
    },
    getPersonList() {
        if(this.currentProject != '') {
            pickupPersonList(this.currentProject).then(res => {
                if (res.code == 200) {
                    let map = new Map();
                    res['data'].forEach((d) => {
                        map.set(d.userName, d.nickName);
                    });
                    this.personObject = Object.fromEntries(map);
                    this.dealPersonList = Object.keys(this.personObject);
                }
            });
        }
    },
    transformTypeObject() {
        let map = new Map();
        this.orderTypeList.forEach((d) => {
            map.set(d.dictCode, d.dictValue);
        });
        this.orderTypeObject = Object.fromEntries(map);
    },
    /** 查询工单明细列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectCode = this.currentProject;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getOrderTypeList(){
      let oderTypeName = this.currentProject+"_gdlx";
      console.log(oderTypeName)
      getDicts(oderTypeName).then(response => {
        console.log('工单列表',response.data);
        this.orderTypeList= response.data;
        this.transformTypeObject();
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
      this.fileProcessList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log('orderQuery')
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工单明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工单明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.projectCode = this.currentProject;
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工单明细编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('workOrder/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    //工单附件上传
    handleSuccess(res, file) {
      console.log(file)
    },
    //处理过程附件上传
    processHandleSuccess(res, file) {
        console.log(file)
    },
    //查看
    check(id) {
      // 根据工单id获取工单信息
      orderDetail(id).then(response => {
        // console.log("调用查看方法,调用接口返回的数据为:",response)
        this.form = response.data;
        for (const oderType of this.orderTypeList) {
          if (this.form.type==oderType.dictCode){
            this.form.type=oderType.dictValue;
            break;
          }
        }
        if(this.form.orderEnclosureList != null && this.form.orderEnclosureList.length > 0) {
          let files = [];
          let processFiles = [];
          this.form.orderEnclosureList.forEach((d) => {
            if(d.type == 1) {
              files.push(d);
            }else if(d.type != 0) {
              processFiles.push(d);
            }
          });
          this.fileList = files;
          this.fileProcessList = processFiles;
        }
        // 根据工单编号 查询工单下的附件信息
        this.open = true;
        this.type = 'view';
        this.title = "查看我的工单";
        this.checkDisabled = true;
      });
    },
    //受理
    acceptCase(number) {
      acceptCaseOrder({
        workNumber: number
      }).then(res => {
        if(res.code == 200) {
          this.getList();
          this.$modal.msgSuccess("受理工单成功");
        }
      });
    },
  },
  watch: {
    // '$route'(to, from) {
    //   // 在路由地址发生变化时执行的代码
    //   // console.log('路由地址发生变化');
    //   // console.log('新的路由地址:', to.path);
    //   // console.log('旧的路由地址:', from.path);
    // }
  },
  created() {
    this.beforeEachHandler = (to, from, next) => {
      // 在路由导航之前执行的代码
      // console.log('order页面即将被打开');
      if (to.path === '/workOrder/order') {
        this.getList();
      }
      next();
    };

    this.$router.beforeEach(this.beforeEachHandler);
  },
  beforeDestroy() {
    const index = this.$router.beforeHooks.indexOf(this.beforeEachHandler);
    if (index !== -1) {
      this.$router.beforeHooks.splice(index, 1);
    }
  }
};
</script>
<style scoped>
  .width_100 {
    width: 100%;
  }
  .a-link {
    color: #409eff;
  }
  ::v-deep .table-diy .el-form-item__content  {
    margin-left: 0 !important;
    margin-top: 10px;
  }
</style>
